package com.neusoft.neuiotms.common.util;

import java.util.List;

import org.springframework.beans.BeanUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ConverterUtil {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * Description: 类之间的复制属性
     *
     * @param t1 源数据
     * @param t2 目标数据
     */
    public static void converter(final Object source, final Object target) {
        BeanUtils.copyProperties(source, target);
    }

    /**
     * Description:将Object转换成json字符串
     *
     * @param Object data
     * @return String
     */
    public static String objectToJson(final Object data) {
        try {
            return ConverterUtil.MAPPER.writeValueAsString(data);
        } catch (final JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Description:将Object转换成实体
     *
     * @param data
     * @param beanType
     * @return
     */
    public static <T> List<T> objectToList(final Object data, final Class<T> beanType) {
        return ConverterUtil.jsonToList(ConverterUtil.objectToJson(data), beanType);
    }

    /**
     * Description:将json数据转换成pojo对象list
     *
     * @param jsonData 数据源
     * @param beanType 实体类
     * @return <T> List<T>
     */
    public static <T> List<T> jsonToList(final String jsonData, final Class<T> beanType) {
        final JavaType javaType = ConverterUtil.MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            final List<T> list = ConverterUtil.MAPPER.readValue(jsonData, javaType);
            return list;
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
